package cn.zero.test;

import cn.zero.utils.ESClientUtil;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

public class EsTest2 {
    //    - 查询用户表
    //    - name包含：我在源码
    //    - age在1~12之间
    //    - 每页大小2
    //    - 从二页开始查
    //    - 按照age倒序
    //    - sex=1
    @Test
    public void testEs() throws Exception{
        //获取连接
        TransportClient client = ESClientUtil.getClient();
        //查询pethome库
        SearchRequestBuilder builder = client.prepareSearch("pethome");
        //type
        builder.setTypes("user");
        //设置查询条件----------------QueryBuilders工具类
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //DSL查询
        boolQuery.must(QueryBuilders.matchQuery("name","我在源码"));
        //DSL过滤
        boolQuery.filter(QueryBuilders.termQuery("sex",1));
        boolQuery.filter(QueryBuilders.rangeQuery("age").gte(1).lte(12));

        //放入query
        builder.setQuery(boolQuery);

        //分页
        //每页条数
        builder.setSize(5);
        //起始位置
        builder.setFrom(5);
        //排序
        builder.addSort("age", SortOrder.DESC);

        //接收结果
        SearchHit[] hits = builder.get().getHits().getHits();
        for (SearchHit hit : hits){
            System.out.println(hit.getSourceAsMap());
        }

    }
}
